<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form @keyup.enter.native='searchQuery'>
        <a-row :gutter='24'>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='日期'>
              <a-input style='width: 100%' placeholder='请输入查询日期,格式为[年份]或者[年份-月份]' v-model='queryParam.salTime'/>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-button type='primary' @click='searchQuery' icon='search'>查询</a-button>
            <a-button type='primary' @click='searchReset' icon='reload' style='margin-left: 8px'>重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <div class='table-operator'>
      <a-button type='primary' icon='download' @click="handleExportXls('税费管理')">导出</a-button>
    </div>
    <div>
      <a-table
        ref='table'
        size='middle'
        :scroll='{x:true}'
        bordered
        rowKey='salTime'
        :columns='columns'
        :dataSource='dataSource'
        :pagination='false'
        :loading='loading'
        class='j-table-force-nowrap'
        @change='handleTableChange'>
        <template #salTime='text,record'>
          <span style='font-weight: bolder'>{{ text }}</span>
        </template>
      </a-table>
      <div style='margin-top: 15px' class="statisticsBox">
        <a-row v-for='(item,index) in statisticsArr' :key='index'>
          <a-col :span='8' v-for='(v,i) in item' :key='i' :style='v.style'>
            <a-card>
              <a-statistic :title='v.title' :value='v.value.toFixed(2)'/>
            </a-card>
          </a-col>
        </a-row>
      </div>
      <a-card bordered style='margin-top: 15px'>
        <div class='body' style='display: flex;flex-direction: column;align-items: center;justify-content: center'>
          <h2 style='font-weight: bolder'>现金流折线图</h2>
          <div id='echarts'></div>
        </div>
      </a-card>

    </div>
    <hf-operation-statistics-modal ref='HfOperationStatisticsModal'></hf-operation-statistics-modal>
    <hf-salary-check-log-list   ref='hfSalaryCheckLogList'></hf-salary-check-log-list>
  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {downFile, getAction} from '@api/manage'
import * as echarts from 'echarts'
import {GridComponent} from 'echarts/components'
import {LineChart} from 'echarts/charts'
import {UniversalTransition} from 'echarts/features'
import {CanvasRenderer} from 'echarts/renderers'
import HfOperationStatisticsModal from './modules/HfOperationStatisticsModal'
import moment from 'moment'
import TableTitleTooltip from "@views/hifar/operate/TableTitleTooltip";
import HfSalaryCheckLogList from '@views/hifar/operate/HfSalaryCheckLogList'

export default {
  name: 'HfOperationOtherCostList',
  mixins: [JeecgListMixin],
  echarts: [GridComponent, LineChart, CanvasRenderer, UniversalTransition],
  components: {
    HfSalaryCheckLogList,
    HfOperationStatisticsModal,
    TableTitleTooltip,

  },
  data() {
    const columns = [
      {
        title: '日期',
        align: 'center',
        width: 100,
        dataIndex: 'salTime',
        scopedSlots: {customRender: 'salTime'}
      },
      {
        title: <span>月度<br/>经营现金流</span>,
        align: 'center',
        dataIndex: 'flow1',
        customRender: (value, row, index) => {
          return index < 12 ?
            <span
              style={{ color: value >= 0 ? "#409EFF" : '#ff0000'}}>{this.formatValue(value)}</span> :
            <span>{this.formatValue(value)}</span>
        }
      },
      {
        title: <span>月度<br/>公司现金流</span>,
        align: 'center',
        dataIndex: 'flow2',
        customRender: (value, row, index) => {
          return index < 12 ?
            <span
              style={{ color: value >= 0 ? "#409EFF" : '#ff0000'}}>{this.formatValue(value)}</span> :
            <span>{this.formatValue(value)}</span>
        }
      },
      {
        title: <span>月度<br/>经营利润</span>,
        align: 'center',
        dataIndex: 'flow5',
        customRender: (value, row, index) => {
          return index < 12 ?
            <span
              style={{ color: value >= 0 ? "#409EFF" : '#ff0000'}}>{this.formatValue(value)}</span> :
            <span>{this.formatValue(value)}</span>
        }
      },
      {
        title: <span>年度累计<br/>经营现金流</span>,
        align: 'center',
        dataIndex: 'flow3',
        customRender: (value, row, index) => {
          return index < 12 ?
            <span
              style={{ color: value >= 0 ? "#409EFF" : '#ff0000'}}>{this.formatValue(value)}</span> :
            <span>{this.formatValue(value)}</span>
        }
      },
      {
        title: <span>年度累计<br/>公司现金流</span>,
        align: 'center',
        dataIndex: 'flow4',
        customRender: (value, row, index) => {
          return index < 12 ?
            <span
              style={{ color: value >= 0 ? "#409EFF" : '#ff0000'}}>{this.formatValue(value)}</span> :
            <span>{this.formatValue(value)}</span>
        }
      },

      {
        title: <span>年度累计<br/>经营利润</span>,
        align: 'center',
        dataIndex: 'flow6',
        customRender: (value, row, index) => {
          return index < 12 ?
            <span
              style={{ color: value >= 0 ? "#409EFF" : '#ff0000'}}>{this.formatValue(value)}</span> :
            <span>{this.formatValue(value)}</span>
        }
      },
      {
        title: '经营收入',
        align: 'center',
        children: [
          {
            title: <TableTitleTooltip title={'合同管理-回款管理'} tableTitle={'合同回款'}/>,
            align: 'center',
            dataIndex: 'a1',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('a1', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 4
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip title={'“财务管理-财税管理”财税小类的收入-经营退税'} tableTitle={'退税'}/>,
            align: 'center',
            dataIndex: 'a2',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('a2', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip title={'“投标管理-保证金管理”退回金额'} tableTitle={'保证金'}/>,
            align: 'center',
            dataIndex: 'a3',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('a3', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip title={'“财务管理-财税管理”财税小类的收入-结息、收入-其他费用分类+“财务管理-费用管理”的负数总和（投融资分类除外）'}
                                      tableTitle={'其他现金'}/>,
            align: 'center',
            dataIndex: 'a4',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('a4', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          }
        ]
      },
      {
        title: '经营支出',
        align: 'center',
        children: [
          {
            title: <TableTitleTooltip title={'“合同管理-付款管理”+“财务管理-报销管理”的成本报销小类'} tableTitle={'采购费用'}/>,
            align: 'center',
            dataIndex: 'b1',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('b1', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 9
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip title={'“财务管理-工资管理”实发工资小类'} tableTitle={'职工薪酬'}/>,
            align: 'center',
            dataIndex: 'b2',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('b2', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip title={'“财务管理-工资管理”五险小类+公积金小类'} tableTitle={'五险一金'}/>,
            align: 'center',
            dataIndex: 'b3',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('b3', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip title={'“财务管理-工资管理”个税小类'} tableTitle={'个税'}/>,
            align: 'center',
            dataIndex: 'b4',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('b4', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip title={'“财务管理-财税管理”财税小类的支出-经营缴税'} tableTitle={'经营税费'}/>,
            align: 'center',
            dataIndex: 'b6',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('b6', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip title={'“财务管理-报销管理”的除成本报销小类外'} tableTitle={'差旅费用'}/>,
            align: 'center',
            dataIndex: 'b7',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('b7', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip title={'“投标管理-保证金管理”当年支付金额'} tableTitle={'保证金'}/>,
            align: 'center',
            dataIndex: 'b8',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('b8', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip
              title={'“财务管理-费用管理”的外联费、市场宣传费、招聘培训费、固定资产费、资质费、日常办公费、福利费、招投标费、评审费、租赁装修物业费、备用金借款、采购费B小类+“财务管理-财税管理”支出-银行手续费、支出-记账费、支出-其他费用'}
              tableTitle={'日常费用'}/>,
            align: 'center',
            dataIndex: 'b9',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('b9', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip title={'“财务管理-费用管理”的非经营性其他费用和经营其他费用正数总和'} tableTitle={'其他费用'}/>,
            align: 'center',
            dataIndex: 'b10',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('b10', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          }
        ]
      },
      {
        title: '投资活动收入',
        align: 'center',
        children: [
          {
            title: <TableTitleTooltip title={'“财务管理-财税管理”财税小类的收入-理财本金'} tableTitle={'理财本金'}/>,
            align: 'center',
            dataIndex: 'c1',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('c1', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 2
              }
              return obj
            }
          },
          {
            title: <TableTitleTooltip title={'“财务管理-财税管理”财税小类的收入-理财所得'} tableTitle={'理财利息'}/>,
            align: 'center',
            dataIndex: 'c2',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('c2', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 0
              }
              return obj
            }
          }
        ]
      },
      {
        title: '投资活动支出',
        align: 'center',
        children: [
          {
            title: <TableTitleTooltip title={'“财务管理-财税管理”财税小类的支出-理财本金'} tableTitle={'理财本金'}/>,
            align: 'center',
            dataIndex: 'd1',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('d1', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 1
              }
              return obj
            }
          }
        ]
      },
      {
        title: '融资收入',
        align: 'center',
        children: [
          {
            title: <TableTitleTooltip title={'“财务管理-费用管理”的投融资小类负数总和'} tableTitle={'融资款'}/>,
            align: 'center',
            dataIndex: 'e1',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('e1', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 1
              }
              return obj
            }
          }
        ]
      },
      {
        title: '融资支出',
        align: 'center',
        children: [
          {
            title: <TableTitleTooltip title={'“财务管理-费用管理”的投融资小类正数总和'} tableTitle={'融资费用'}/>,
            align: 'center',
            dataIndex: 'f1',
            customRender: (value, row, index) => {
              const obj = {
                children: index < 12 && row.salTime !== '小计' && row.salTime !== '合计' ? <a onClick={() => {
                  this.detail('f1', row.salTime)
                }}>{this.formatValue(value)}</a> : this.formatValue(value),
                attrs: {}
              }
              if (index === 13) {
                obj.attrs.colSpan = 1
              }
              return obj
            }
          }
        ]
      }
    ]
    return {
      description: '税费管理管理页面',
      statisticsArr: [
        [
          {
            title: '经营现金流（元）',
            value: 0,
            key: 'operationalCashFlow',
            style: {'margin-right': '5px', 'margin-bottom': '5px'}
          },
          {
            title: '公司现金流（元）',
            value: 0,
            key: 'companyCashFlow',
            style: {marginRight: '5px', marginBottom: '5px'}
          },
          {
            title: '经营利润（元）',
            value: 0,
            key: 'earnedProfit',
            style: {marginRight: '0px', marginBottom: '5px'}
          }
        ],
        [
          {
            title: '待收款（元）',
            value: 0,
            key: 'countExpectMoney',
            style: {marginRight: '5px'}
          },
          {
            title: '净待收款（元）',
            value: 0,
            key: 'countPaymentMoneySum',
            style: {marginRight: '5px'}
          },
          {
            title: '本年合同额（元）',
            value: 0,
            key: 'countContractMoney',
            style: {marginRight: '0px'}
          }
        ]
      ],
      activeKey: 1,
      columns: columns,
      ipagination: {
        current: 1,
        pageSize: 12
      },
      url: {
        list: '/ps/hfPsSalary/statistics',
        sum: '/ps/hfPsSalary/statisticsSum',
        exportData: '/ps/hfPsSalary/statisticsExportData'
      },
      operationalCashFlow_echarts: [],
      companyCashFlow_echarts: [],
      operationFlow: 0,
      companyFlow: 0
    }
  },
  mounted() {

  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    formatValue(value) {
      return value ?  String(value.toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : value
    },
    detail(row, salTime) {
      this.$refs.HfOperationStatisticsModal.open(row, salTime)
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '公司现金流数据报表'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportData, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], {type: 'application/vnd.ms-excel'}), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], {type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },

    loadData() {
      let params = this.getQueryParams()//查询条件
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.operationalCashFlow_echarts = []
          this.companyCashFlow_echarts = []
          for (let i = 0; i < this.dataSource.length; i++) {
            if (i < 12) {
              let {a1, a2, a3, a4, b1, b2, b3, b4, b6, b7, b8, b9, b10, c1, c2, d1, e1, f1} = this.dataSource[i]
              let X1 = a1 + a2 + a3 + a4
              let X2 = b1 + b2 + b3 + b4 + b6 + b7 + b8 + b9 + b10
              let X3 = c1 + c2
              let X4 = d1
              let X5 = e1
              let X6 = f1
              let operationalCashFlow = X1 - X2
              let companyCashFlow = X1 + X3 + X5 - X2 - X4 - X6
              this.operationalCashFlow_echarts.push(operationalCashFlow.toFixed(2))
              this.companyCashFlow_echarts.push(companyCashFlow.toFixed(2))
            }
          }
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
        this.getSum(params)
        this.buildEcharts()
      })
    },
    buildEcharts() {
      let chartDom = document.getElementById('echarts')
      let myChart = echarts.init(chartDom)
      let option
      option = {
        title: {
          text: ''
        },
        toolbox: {
          feature: {
            dataView: {show: true, readOnly: false},
            magicType: {
              show: true, type: ['line', 'bar']
            },
            restore: {show: true},
            saveAsImage: {
              name: '经营现金流'
            }
          },
          right: 20
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['经营现金流', '公司现金流']
        },
        xAxis: {
          type: 'category',
          name: '月份',
          nameTextStyle: {
            fontWeight: 'bolder',
            fontSize: '16px'
          },
          data: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          name: '元',
          nameTextStyle: {
            fontWeight: 'bolder',
            fontSize: '16px'
          }
        },
        series: [
          {
            name: '经营现金流',
            data: this.operationalCashFlow_echarts,
            type: 'line'
          },
          {
            name: '公司现金流',
            type: 'line',
            stack: 'Total',
            data: this.companyCashFlow_echarts
          }
        ]
      }
      option && myChart.setOption(option)
    },
    getSum(params) {
      getAction(this.url.sum, params).then(res => {
        if (res.success) {
          let obj = res.result
          let X1 = obj.A1 + obj.A2 + obj.A3 + obj.A4
          let X2 = obj.B1 + obj.B2 + obj.B3 + obj.B4 + obj.B6 + obj.B7 + obj.B8 + obj.B9 + obj.B10
          let X3 = obj.C1 + obj.C2
          let X4 = obj.D1
          let X5 = obj.E1
          let X6 = obj.F1
          // 计算经营现金流
          obj.operationalCashFlow = X1 - X2
          // 计算公司现金流
          obj.companyCashFlow = X1 + X3 + X5 - X2 - X4 - X6
          // 计算经营利润
          obj.earnedProfit = obj.operationalCashFlow - obj.A3 - obj.A4 + obj.B8 + obj.B10
          // 计算净收款
          obj.countPaymentMoneySum = obj.countExpectMoney - obj.countPaymentMoney
          this.statisticsArr.forEach(item => {
            item.forEach(v => {
              for (let key in obj) {
                if (v.key === key) {
                  v.value = obj[key]
                }
              }
            })
          })
        }
      })
    }
  },
  handleChangeTabs(key) {
    console.log(key)
  }


}
</script>
<style scoped lang='less'>
@import '~@assets/less/common.less';

#echarts {
  width: 100%;
  height: 500px;
  /*border: 1px solid red;*/
  margin: 0 auto;
}

/deep/ .ant-table-header-column {
  font-weight: bolder;
}

/deep/ .ant-row {
  display: flex;
}

/deep/ .table-page-search-wrapper {
  .ant-form-item-control-wrapper {
    flex: 1;
  }
}

/deep/ .statisticsBox {
  .ant-col {
    flex: 1;
  }
}


.jee-hidden {
  display: none !important;
}
</style>